package com.benzhitech;

import com.benzhitech.core.Router;
import com.benzhitech.core.RouteHandler;
import com.benzhitech.core.StaticResourceHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.handler.codec.http.HttpMethod;

/**
 * 处理 HTTP 请求的核心 Handler。
 * 使用 Router 将请求分发给对应的 RouteHandler。
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final Logger log = LoggerFactory.getLogger(HttpServerHandler.class);
    private final Router router;

    /**
     * 构造函数，传入 Router 实例。
     * @param router 路由管理器
     */
    public HttpServerHandler(Router router) {
        this.router = router;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        String uri = request.uri();
        HttpMethod method = request.method();
        log.info("接收到 HTTP 请求: URI={}, Method={}", uri, method);
        
        // 特殊处理：检查是否为静态资源请求
        if (StaticResourceHandler.isStaticResourceRequest(uri)) {
            log.info("检测到静态资源请求: {}", uri);
            FullHttpResponse response = StaticResourceHandler.handleRequest(ctx, request);
            sendResponse(ctx, response, request);
            return;
        }

        // 查找路由处理器
        RouteHandler handler = router.findHandler(method, uri);

        FullHttpResponse response;
        if (handler != null) {
            try {
                // 调用找到的 Handler 处理请求
                response = handler.handle(ctx, request);
            } catch (Exception e) {
                log.error("处理请求时发生异常: URI={}, Method={}", uri, method, e);
                response = createErrorResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Internal Server Error: " + e.getMessage());
            }
        } else {
            // 未找到对应的 Handler，返回 404
            log.warn("未找到处理器: URI={}, Method={}", uri, method);
            response = createErrorResponse(HttpResponseStatus.NOT_FOUND, "Not Found: " + uri);
        }

        // 发送响应
        sendResponse(ctx, response, request);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("Channel Pipeline 中发生异常", cause);
        FullHttpResponse response = createErrorResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Internal Server Error: " + cause.getMessage());
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        // ctx.close(); // ChannelFutureListener.CLOSE 会关闭
    }

    /**
     * 创建错误响应的辅助方法。
     */
    private FullHttpResponse createErrorResponse(HttpResponseStatus status, String message) {
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                status,
                Unpooled.copiedBuffer(message, CharsetUtil.UTF_8));
        response.headers().set("Content-Type", "text/plain; charset=UTF-8");
        response.headers().set("Content-Length", response.content().readableBytes());
        return response;
    }

    /**
     * 发送 HTTP 响应
     */
    private void sendResponse(ChannelHandlerContext ctx, FullHttpResponse response, FullHttpRequest request) {
        if (response != null) {
            // TODO: 处理 Keep-Alive
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }
} 